#include <QSqlRecord>
#include "lqsqlrelationaltablemodel.h"

LQSqlRelationalTableModel::LQSqlRelationalTableModel(QObject *parent, QSqlDatabase db)
    : QSqlRelationalTableModel(parent, db)
{
}

LQSqlRelationalTableModel::~LQSqlRelationalTableModel()
{
}

bool LQSqlRelationalTableModel::select()
{
    bool ret = QSqlRelationalTableModel::select();

    if (ret)
        generateRoleNames();

    return ret;
}

void LQSqlRelationalTableModel::generateRoleNames()
{
    role_names.clear();

    for (int i = 0; i < record().count(); ++i)
    {
        role_names[Qt::UserRole + i + 1] = record().fieldName(i).toUtf8();
    }
}

QVariant LQSqlRelationalTableModel::data(const QModelIndex &item, int role) const
{
    if (item.row() >= rowCount())
        return QString();

    if (role < Qt::UserRole)
        return QSqlQueryModel::data(item, role);
    else
    {
        int columnIdx = role - Qt::UserRole - 1;
        QModelIndex modelIndex = this->index(item.row(), columnIdx);
        return QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
    }
}
